package com.sound.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.sound.common.MyValidationUtils;
import com.sound.common.Response;
import com.sound.model.*;
import com.sound.service.RedisService;
import com.sound.service.TypeService;
import com.sound.vo.TypeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.sound.service.AlbumService;
import com.sound.service.AudioService;
import com.sound.vo.CollectVo;

@RestController
@Api(tags="收藏")
@RequestMapping(path = "/collect")
public class CollectController extends BaseController<CollectModel> {

	private static final Logger logger = LoggerFactory.getLogger(CollectController.class);

	@Autowired
	private AlbumService albumService;

	@Autowired
	private AudioService audioService;

	@Autowired
	private TypeService typeService;

	@Autowired
	private RedisService redisService;



	/**
	 * 如果是正常的bigType就传bigType 如果是音频,bigType就传0
	 * 
	 */
	@GetMapping(path = "/save")
	@ApiOperation(value = "收藏音频或者音频")
	public Response<CollectModel> save(HttpServletRequest req,Long id,Boolean isAlbum) {
		UserModel userModel = redisService.getUserInfo(req);
		CollectModel model = new CollectModel();
		model.setUserId(userModel.getUserId());
		System.out.println("userId:"+userModel.getUserId());
		model.setIsAlbum(isAlbum);
		model.setObjId(id);
		Long tmpid =id;
		try{
			Example<CollectModel> example = Example.of(model);
			Iterator<CollectModel> ite = super.service.findAll(example).iterator();
			if(ite.hasNext()){
				Response<CollectModel> resp = new Response<CollectModel>(true);
				resp.setMsg("已在收藏中");
				return resp;
			}
			if(!isAlbum){
				AudioModel model1 = audioService.findById(id);
				tmpid = model1.getAlbumId();
			}

			AlbumModel model1 = albumService.findById(tmpid);
			if(model1 == null){
				return new Response<CollectModel>(false);
			}
			TypeModel type = typeService.findById(model1.getTypeId());
			if(type != null){
				if(type.getBigTypeId()==21 || type.getBigTypeId()==22 || type.getBigTypeId()==19)
					model.setBigTypeId(type.getBigTypeId());
				else
					model.setBigTypeId(999L);
			}else{
				return new Response<CollectModel>(false);
			}

			model.setUserId(userModel.getUserId());
			super.service.save(model);
			return new Response<CollectModel>(true);
		}catch (Exception e){
			logger.error("save fail:",e);
		}
			return new Response<CollectModel>(false);

	}
	
	@GetMapping(path = "/exist")
	public Response<Boolean> exist(CollectModel t){
		Response<Boolean> resp = new Response<Boolean>(true);
		try {
			Response<Iterable<CollectModel>> tmp = super.findAll(t);
			resp.setData(tmp.getData().iterator().hasNext());
		}catch(Exception e) {
			logger.error("exist fail:",e);
			resp = new Response<Boolean>(false);
		}
		return resp;
	}

	@GetMapping(path = "/findByExample")
	@ApiOperation(value = "收藏列表，专栏bigtypeId=999")
	public Response<CollectVo> findBy(HttpServletRequest req,Long bigTypeId,Boolean isAlbum) {

		UserModel userModel = redisService.getUserInfo(req);
		CollectModel ex = new CollectModel();
		ex.setBigTypeId(bigTypeId);
		ex.setIsAlbum(isAlbum);
		ex.setUserId(userModel.getUserId());
		Example<CollectModel> example = Example.of(ex);

		Response<CollectVo> resp = new Response<CollectVo>(true);
		try{

			Iterator<CollectModel> modelIterator = service.findAll(example).iterator();
			List<CollectVo> listVo = new ArrayList<CollectVo>();

			if(ex.getIsAlbum()) {
				List<Long> albumIds = new ArrayList<Long>();
				while (modelIterator.hasNext()) {
					CollectModel cm = modelIterator.next();
					albumIds.add(cm.getObjId());
					
				}
				Iterable<AlbumModel> albums = albumService.findAllById(albumIds);
				CollectVo<AlbumModel> collectVo = new CollectVo<AlbumModel>();
				collectVo.setList(albums);
				
				resp.setData(collectVo);

			}else {
				List<Long> audioIds = new ArrayList<Long>();
				while (modelIterator.hasNext()) {
					CollectModel cm = modelIterator.next();
					audioIds.add(cm.getObjId());
				}
				Iterable<AudioModel> audios =  audioService.findAllById(audioIds);
				CollectVo<AudioModel> collectVo = new CollectVo<AudioModel>();
				
				collectVo.setList(audios);
				resp.setData(collectVo);
			}
		}catch (Exception e){
			logger.error("findByExample fail:",e);
			resp = new Response<CollectVo>(false);
		}

		return resp;
	}
/*
	@GetMapping(path = "/deleteById")
	public Response<Void> deleteById(String ids) {
		String[] idstr = ids.split(",");
		List<Long> idsList= new ArrayList<>();
		for(String ss:idstr){
			idsList.add(Long.valueOf(ss));
		}
		try {
			Iterable<CollectModel> collect = super.service.findAllById(idsList);
			super.service.deleteInBatch(collect);
		}catch (Exception e){
			logger.info("deleteById fail",e);
		}
		return new Response<Void>(true);
	}
*/
	@GetMapping(path = "/delete")
	@ApiOperation(value = "删除收藏")
	public Response<Void> deleteById(@RequestParam("objId")Long objId,@RequestParam("isAlbum")Boolean isAlbum,HttpServletRequest req ) {
		CollectModel collectModel = new CollectModel();
		collectModel.setObjId(objId);
		collectModel.setIsAlbum(isAlbum);
		UserModel userModel = redisService.getUserInfo(req);
		collectModel.setUserId(userModel.getUserId());
		try {

			Iterable<CollectModel> iter = super.service.findAll(Example.of(collectModel));
			Iterator	<CollectModel> iters = iter.iterator();
			while(iters.hasNext()) {
				collectModel = iters.next();
				super.service.delete(collectModel);
			}
		}catch(Exception e) {
			logger.error("findByExample fail:",e);
			return new Response<Void>(false,e.getMessage());
		}
		
		return new Response<Void>(true);
	}
}
